home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4184 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.1 KB  |  74 lines

  1. Path: ub239.dialup.uwa.edu.au!not-for-mail
  2. From: prye@cyllene.uwa.edu.au (Peter Rye)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: precision methods
  5. Date: 29 Jan 1996 00:53:53 +0800
  6. Organization: The University of Western Australia
  7. Message-ID: <4eg9n1$24u@ub239.dialup.uwa.edu.au>
  8. References: <4ebq07$54r@sun.cis.smu.edu>
  9. NNTP-Posting-Host: ub239.dialup.uwa.edu.au
  10.  
  11. dbowman@post.smu.edu (Damon Bowman) writes:
  12.  
  13. >How is the precision member functions supposed to work?  The book says
  14. >that it controls the number of places to the RIGHT of the decimal.  In
  15. >other words, 
  16.  
  17. >float a = 45.67;
  18. >cout.precision(2);
  19. >cout << a;
  20.  
  21. >Should output 45.67.  It actually outputs 46 on my machine.  Is the
  22. >book wrong (wouldn't be the first time I've found blatant errors in
  23. >programming books).
  24.  
  25. This is what it does here also.
  26. The setting of precision does slightly different things depending on
  27. how the other ios flags are set.
  28. In my case and presumably yours, 'ios::fixed' is unset as the default.
  29. In this case precision will set the number of *significant digits* in
  30. the output.  If ios::fixed is set, it will give you the number of 
  31. digits to the right of the decimal place.
  32.  
  33. eg:
  34.  
  35. ub239:~$ cat test1.cpp
  36. #include<iostream.h>
  37. #include<iomanip.h>
  38.  
  39. int main() {
  40.  
  41.     float x = 46.35923;
  42.  
  43.     cout.setf(ios::fixed);
  44.     cout.precision(5);
  45.     cout << x << endl;
  46.  
  47.     cout.unsetf(ios::fixed);
  48.     cout << x << endl;
  49.  
  50.     return 0;
  51. }
  52. ub239:~$ g++ -Wall test1.cpp
  53. ub239:~$ a.out
  54. 46.35923
  55. 46.359
  56.  
  57.  
  58. >d:\msvc\test\fig11_17.cpp(21) : warning C4270: 'initializing' : do not
  59. >initialize a non-const 'class ::__SMANIP_int __near &' with a
  60. >non-lvalue 'class ::__SMANIP_int ' function return
  61.  
  62. Can't help sorry. I get no warnings/errors with your code here.
  63. The code doesn't give the results as depicted in the book though (I've
  64. got Deitel & Deitel too), but does give the results you'd expect as
  65. explained above.
  66.  
  67. Regards,
  68. Peter Rye
  69. -- 
  70. | Peter Rye                                                           |
  71. | Respiratory Research Fellow                                         |
  72. | Princess Margaret Hospital for Children                             |
  73. | Perth, Western Australia                                            |
  74.